package com.Service;
import com.Dao.GetUserDao;
import com.Dao.Imp.GetUserDaoImp;
import com.Dao.Imp.UpdateUserDaoImp;
import com.Dao.UpdateUserDao;
import com.Utils.RedisUtil;
import com.common.Result;
import com.pojo.PwdResetDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
@Service
@Slf4j
public class LoginService {
    //登录短信验证码缓存key前缀
    private final static String LOGIN_SMS_CODE_KEY_PRE = "LOGIN_SMS_CODE:%s";
    //密码重置短信验证码缓存key前缀
    private final static String RESET_SMS_CODE_KEY_PRE = "RESET_SMS_CODE:%s";
    @Autowired
    private RedisUtil redisUtil;

    public Result login(String username, String pwd, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");//防止用户输入中文导致乱码
        resp.setContentType("text/html;charset=UTF-8");//防止浏览器端乱码
        GetUserDao getUserDao = new GetUserDaoImp();
        int loginFlag = 0;
        try {
            loginFlag = getUserDao.getUser(username, pwd);
            switch (loginFlag) {
                case 1:
                    HttpSession session = req.getSession();
                    session.setAttribute("username", username);
                    break;
                case 2:
                    resp.sendRedirect("/?error=fail");
                    break;
                case 3:
                    resp.sendRedirect("/?error=pleLogin");
                case 4:
                    resp.sendRedirect("/?error=forbid");
            }
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        return new Result().ok("success");
    }
    public Result noPwdLogin(String phoneNumber, String confirmCode, HttpServletRequest req, HttpServletResponse resp) {
        GetUserDao getUserDao = new GetUserDaoImp();
        try {
            //校验数据库中是否存在该手机号账号
            int loginFlag = getUserDao.getUser(phoneNumber);
            if (1 != loginFlag) {//不存在
                return new Result().error("账号不存在请注册");
            }
            //从缓存中获取该手机号对应登录类型的验证码缓存值
            Object codeCache = redisUtil.get(String.format(LOGIN_SMS_CODE_KEY_PRE, phoneNumber));
            if (ObjectUtils.isEmpty(codeCache) || !confirmCode.equals(String.valueOf(codeCache))) {
                return new Result().error("验证码错误或已过期");
            }
            //登录成功 将当前用户存入当前会话中
            HttpSession session = req.getSession();
            session.setAttribute("username", phoneNumber);
            return new Result().ok("success");
        } catch (Exception e) {
            log.error("手机号登录异常:{}", e.getMessage(), e);
            return new Result().error("手机号登录失败");
        }
    }

    public Result passwordReset(PwdResetDTO resetDTO) {
        GetUserDao getUserDao = new GetUserDaoImp();
        try {
            //校验数据库中是否存在该手机号账号
            int loginFlag = getUserDao.getUser(resetDTO.getUsername());
            if (1 != loginFlag) {
                return new Result().error("账号不存在请注册");
            }
            //从缓存中获取该手机号对应密码重置类型的验证码缓存值
            Object codeCache = redisUtil.get(String.format(RESET_SMS_CODE_KEY_PRE, resetDTO.getUsername()));
            if (ObjectUtils.isEmpty(codeCache) || !resetDTO.getConfirmCode().equals(String.valueOf(codeCache))) {
                return new Result().error("验证码错误或已过期");
            }
            //执行修改密码sql语句
            UpdateUserDao updateUserDao = new UpdateUserDaoImp();
            int flag = 0;
            try {
                flag = updateUserDao.update(resetDTO.getUsername(), resetDTO.getPassword());
            } catch (SQLException e) {
                return new Result().error("密码重置失败");
            }
            if (flag == -1) {//账户不存在，提示注册账户
                return new Result().error("账户不存在，请注册账户");
            }
            return new Result().ok("success");
        } catch (Exception e) {
            log.error("手机号登录异常:{}", e.getMessage(), e);
            return new Result().error("密码重置失败");
        }
    }

}
